<template>
	<view class="container">
		<view class="header">
			<text class="title">工时记录</text>
			<view class="filter-button" @click.stop="showFilterMenu">
				<image class="icon-more" :src="'/static/image/' + (showFilter ? 'more-active.png' : 'more.png')"></image>
			</view>
			<view class="header-info">
				<text>本月工时: {{monthlyStats.totalHours}}小时</text>
				<text>预计工资: ¥{{monthlyStats.totalAmount}}</text>
			</view>
		</view>

		<!-- 遮罩层，用于点击关闭菜单 -->
		<view class="filter-mask" v-if="showFilter" @click.stop="showFilter = false"></view>

		<!-- 筛选菜单 -->
		<view class="filter-menu" v-if="showFilter" @click.stop>
			<view class="filter-option" @click="toggleMonthFilter">
				<text>{{ monthFilter ? '显示所有记录' : '只看本月记录' }}</text>
				<text class="check" v-if="monthFilter">✓</text>
			</view>
			<view class="filter-option" @click="setSortOrder('asc')">
				<text>时间升序</text>
				<text class="check" v-if="sortOrder === 'asc'">✓</text>
			</view>
			<view class="filter-option" @click="setSortOrder('desc')">
				<text>时间降序</text>
				<text class="check" v-if="sortOrder === 'desc'">✓</text>
			</view>
		</view>

		<view class="record-list">
			<view v-for="(group, date) in groupedRecords" :key="date" class="date-group">
				<view class="date-header">
					<text class="date">{{date}}</text>
					<text class="total">共{{group.totalHours.toFixed(1)}}小时</text>
				</view>
				
				<view v-for="(record, index) in group.records" :key="record.id" class="record-item-container">
					<view class="record-item" 
						@touchstart="touchStart($event, record)"
						@touchmove="touchMove($event, record)" 
						@touchend="touchEnd(record)">
						<view class="record-content" :style="{transform: `translateX(${record.slideX}px)`}">
							<view class="time-slot">
								<text :class="['period', record.period]">{{getPeriodText(record.period)}}</text>
							</view>
							<view class="content">
								<view class="content-header">
									<text class="hours">{{record.hours}}小时</text>
									<text class="wage">¥{{calculateWage(record)}}</text>
								</view>
								<text class="description">{{record.content || '暂无内容'}}</text>
							</view>
						</view>
						<view class="action-buttons">
							<button class="btn-edit" @click="editRecord(record)">编辑</button>
							<button class="btn-delete" @click="handleDelete(record)">删除</button>
						</view>
					</view>
				</view>
			</view>
			
			<view v-if="Object.keys(groupedRecords).length === 0" class="empty-tip">
				暂无工时记录，点击右下角按钮添加
			</view>
			
			<!-- 添加浮动按钮 -->
			<view class="float-button" @click="addRecord">
				<text class="plus">+</text>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapState, mapGetters, mapActions } from 'vuex'

	export default {
		data() {
			return {
				groupedRecords: {},
				startX: 0,
				showFilter: false,
				monthFilter: false,
				sortOrder: 'desc', // 默认降序（最新的记录在前面）
			}
		},
		computed: {
			...mapState(['records', 'currentMonth']),
			...mapGetters(['monthlyStats'])
		},

		// 修改生命周期钩子
		onShow() {
			this.loadData()
		},
		onLoad() {
			this.loadData()
			// 添加点击页面任意位置关闭筛选菜单的事件
			const page = this.$scope || this.$mp?.page || this
			if (page) {
				page.$vm = page.$vm || {}
				page.$vm.closeFilter = () => {
					if (this.showFilter) {
						this.showFilter = false
					}
				}
			}
		},

		methods: {
			...mapActions(['loadRecords', 'deleteRecord']),
			
			// 修改数据加载方法
			async loadData() {
				try {
					await this.loadRecords()
					await this.groupRecords()
				} catch (error) {
					console.error('加载数据失败:', error)
					uni.showToast({
						title: '加载失败',
						icon: 'none',
						duration: 2000
					})
				}
			},
			
			showFilterMenu() {
				this.showFilter = !this.showFilter
			},
			
			toggleMonthFilter() {
				this.monthFilter = !this.monthFilter
				this.groupRecords()
				this.showFilter = false
			},
			
			setSortOrder(order) {
				this.sortOrder = order
				this.groupRecords()
				this.showFilter = false
			},
			
			calculateWage(record) {
				const hours = parseFloat(record.hours) || 0
				const rate = parseFloat(record.hourlyRate)
				return (hours * (rate === 0 ? 0 : (rate || 30))).toFixed(2)
			},
			
			touchStart(e, record) {
				this.startX = e.touches[0].pageX
				
				// 重置其他记录的滑动状态
				Object.keys(this.groupedRecords).forEach(date => {
					this.groupedRecords[date].records.forEach(item => {
						if (item.id !== record.id && item.slideX !== 0) {
							item.slideX = 0
						}
					})
				})
			},
			
			// 优化滑动操作
			touchMove(e, record) {
				const moveX = e.touches[0].pageX - this.startX
				const slideX = Math.min(0, Math.max(-120, moveX))
				// 添加防抖动
				if (Math.abs(moveX) > 10) { // 只有滑动距离超过10px才触发
					record.slideX = slideX
				}
			},
			
			touchEnd(record) {
				if (record.slideX > -60) {
					record.slideX = 0
				} else {
					record.slideX = -120
				}
			},
			
			// 优化分组记录方法
			async groupRecords() {
				return new Promise((resolve, reject) => {
					try {
						if (!this.records) {
							this.groupedRecords = {}
							resolve()
							return
						}
						
						const groups = {}
						let filteredRecords = [...this.records]
						
						// 应用月份筛选
						if (this.monthFilter) {
							const [year, month] = this.currentMonth.split('-').map(Number)
							filteredRecords = filteredRecords.filter(record => {
								const [recordYear, recordMonth] = record.date.split('-').map(Number)
								return recordYear === year && recordMonth === month
							})
						}
						
						// 分组和计算
						filteredRecords.forEach(record => {
							if (!groups[record.date]) {
								groups[record.date] = {
									records: [],
									totalHours: 0
								}
							}
							groups[record.date].records.push({
								...record,
								slideX: 0
							})
							groups[record.date].totalHours += parseFloat(record.hours) || 0
						})
						
						// 排序
						this.groupedRecords = Object.keys(groups)
							.sort((a, b) => {
								const dateA = new Date(a).getTime()
								const dateB = new Date(b).getTime()
								return this.sortOrder === 'asc' ? dateA - dateB : dateB - dateA
							})
							.reduce((acc, date) => {
								acc[date] = groups[date]
								return acc
							}, {})
						
						resolve()
					} catch (error) {
						console.error('分组记录失败:', error)
						this.groupedRecords = {}
						reject(error)
					}
				})
			},
			
			getPeriodText(period) {
				const texts = {
					morning: '上午',
					afternoon: '下午',
					overtime: '加班'
				}
				return texts[period] || period
			},
			
			editRecord(record) {
				uni.navigateTo({
					url: '/pages/record-edit/record-edit?id=' + record.id
				})
			},
			
			// 优化删除操作
			async handleDelete(record) {
				try {
					await new Promise((resolve, reject) => {
						uni.showModal({
							title: '确认删除',
							content: '是否删除该记录？',
							success: (res) => {
								if (res.confirm) {
									resolve()
								} else {
									reject()
								}
							}
						})
					})
					
					await this.deleteRecord(record.id)
					this.groupRecords()
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					})
				} catch (e) {
					console.error('删除失败:', e)
				}
			},
			
			addRecord() {
				uni.navigateTo({
					url: '/pages/record-edit/record-edit'
				})
			}
		}
	}
</script>

<style>
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.header {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
		position: relative;
	}

	.title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.filter-button {
		position: absolute;
		right: 30rpx;
		top: 30rpx;
		width: 40rpx;
		height: 40rpx;
	}

	.icon-more {
		width: 100%;
		height: 100%;
	}

	.header-info {
		margin-top: 10rpx;
		font-size: 28rpx;
		color: #666;
	}

	.header-info text {
		margin-right: 20rpx;
	}

	.filter-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 90;
	}

	.filter-menu {
		position: absolute;
		right: 20rpx;
		top: 140rpx;
		background-color: #fff;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		z-index: 100;
		padding: 20rpx 0;
		width: 300rpx;
	}

	.filter-option {
		padding: 20rpx 30rpx;
		font-size: 28rpx;
		color: #333;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.filter-option:active {
		background-color: #f5f5f5;
	}

	.check {
		color: #2196f3;
	}

	.date-group {
		margin-bottom: 20rpx;
	}

	.date-header {
		padding: 20rpx;
		background-color: #fff;
		border-radius: 10rpx 10rpx 0 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.date {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}

	.total {
		font-size: 24rpx;
		color: #666;
	}

	.record-item-container {
		position: relative;
		margin-bottom: 2rpx;
		background-color: #fff;
		overflow: hidden;
		height: 140rpx;
	}

	.record-item {
		width: 100%;
		height: 100%;
		position: relative;
		overflow: hidden;
	}

	.record-content {
		position: absolute;
		width: 100%;
		height: 100%;
		left: 0;
		display: flex;
		align-items: flex-start;
		background-color: #fff;
		padding: 20rpx;
		box-sizing: border-box;
		transition: transform 0.3s ease;
		z-index: 2;
	}

	.time-slot {
		width: 100rpx;
		flex-shrink: 0;
	}

	.period {
		font-size: 24rpx;
		padding: 4rpx 12rpx;
		border-radius: 4rpx;
	}

	.period.morning {
		background-color: #e8f5e9;
		color: #4caf50;
	}

	.period.afternoon {
		background-color: #e3f2fd;
		color: #2196f3;
	}

	.period.overtime {
		background-color: #fce4ec;
		color: #e91e63;
	}

	.content {
		flex: 1;
		margin-left: 20rpx;
		overflow: hidden;
	}

	.content-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.hours {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}

	.wage {
		font-size: 28rpx;
		color: #2196f3;
		font-weight: bold;
	}

	.description {
		font-size: 26rpx;
		color: #666;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.action-buttons {
		position: absolute;
		right: 0;
		top: 0;
		height: 100%;
		display: flex;
		align-items: center;
		z-index: 1;
	}

	.btn-edit, .btn-delete {
		width: 120rpx;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
		font-size: 28rpx;
		margin: 0;
		border-radius: 0;
	}

	.btn-edit {
		background-color: #2196f3;
	}

	.btn-delete {
		background-color: #f44336;
	}

	.empty-tip {
		text-align: center;
		color: #999;
		font-size: 28rpx;
		padding: 100rpx 0;
	}

	.float-button {
		position: fixed;
		right: 40rpx;
		bottom: 120rpx; /* 增加底部距离，避免被导航栏遮挡 */
		width: 100rpx;
		height: 100rpx;
		background-color: #2196f3;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.2);
		z-index: 999; /* 确保在最上层 */
	}
	
	.plus {
		color: #fff;
		font-size: 48rpx;
		font-weight: bold;
	}
</style>